package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import distribution.CombinationConfig;

public class MainUtils {

	public static synchronized void saveConfig(CombinationConfig config) {
		ObjectOutputStream oos = null;
		try {
			File dir = new File(System.getProperty("user.home"));
			oos = new ObjectOutputStream(new FileOutputStream(new File(dir,
					"dcball.dat")));
			oos.writeObject(config);
			oos.flush();
		} catch (IOException ex) {
		} finally {
			try {
				oos.close();
			} catch (Exception ex) {
			}
		}
	}

	public static synchronized CombinationConfig readConfig() {
		ObjectInputStream ois = null;
		CombinationConfig config;
		File dir = new File(System.getProperty("user.home"));
		File file = new File(dir, "dcball.dat");
		if (file == null || !file.exists()) {
			// 如果文件不存在,保存一个空白的
			return createEmptyConfiguration();
		} else {
			try {
				ois = new ObjectInputStream(new FileInputStream(file));
				config = (CombinationConfig) ois.readObject();
				if (config == null) {
					config = new CombinationConfig();
					saveConfig(config);
				}
				return config;
			} catch (Exception ex) {
				System.out.println(ex);
				return createEmptyConfiguration();
			} finally {
				try {
					ois.close();
				} catch (Exception ex) {
				}
			}
		}
	}

	private static CombinationConfig createEmptyConfiguration() {
		CombinationConfig config = new CombinationConfig();
		saveConfig(config);
		return config;
	}
	
	
	public static void main(String[] args){
		
	}
}
